package cn.migu.music.hangupsms.cachemanage;

import cn.migu.music.common.service.async.ContextAwareThreadPoolTaskExecutor;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author fgb
 */
@Configuration
public class CacheConfiguration {
    @Bean("cacheRabbitMessageConverter")
    public MessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean("cacheRabbitListenerContainerFactory")
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory,
                                                                               SimpleRabbitListenerContainerFactoryConfigurer configurer,
                                                                               MessageConverter cacheRabbitMessageConverter) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setMessageConverter(cacheRabbitMessageConverter);
        return factory;
    }


    /**
     * 执行缓存通知和处理通知事件线程池
     */
    @Bean("cacheBroadcastExecutor")
    public Executor cacheBroadcastExecutor() {
        ThreadPoolTaskExecutor cacheBroadcastExecutor = new ContextAwareThreadPoolTaskExecutor();
        cacheBroadcastExecutor.setCorePoolSize(3);
        cacheBroadcastExecutor.setMaxPoolSize(10);
        cacheBroadcastExecutor.setKeepAliveSeconds(60);
        cacheBroadcastExecutor.setQueueCapacity(100);
        cacheBroadcastExecutor.setAllowCoreThreadTimeOut(true);
        cacheBroadcastExecutor.initialize();

        return cacheBroadcastExecutor;
    }

    /**
     * 执行缓存通知和处理通知事件线程池
     */
    @Bean("cacheEventHandlerExecutor")
    public Executor cacheEventHandlerExecutor() {
        ThreadPoolTaskExecutor cacheEventHandlerExecutor = new ContextAwareThreadPoolTaskExecutor();
        cacheEventHandlerExecutor.setCorePoolSize(3);
        cacheEventHandlerExecutor.setMaxPoolSize(10);
        cacheEventHandlerExecutor.setKeepAliveSeconds(60);
        cacheEventHandlerExecutor.setQueueCapacity(100);
        cacheEventHandlerExecutor.setAllowCoreThreadTimeOut(true);
        cacheEventHandlerExecutor.initialize();

        return cacheEventHandlerExecutor;
    }
}
